/**
 * User: denis
 * Date: Mar 27, 2009
 */
package ua.com.stormlabs.jsitemapper;

import org.apache.log4j.Logger;
import org.apache.commons.lang.StringUtils;

import java.util.*;
import java.util.regex.Pattern;


public class LinkPreprocessor {

    private static final Logger log = Logger.getLogger(LinkPreprocessor.class);

    private static LinkPreprocessor instance = new LinkPreprocessor();

    private final List<String> retainParamsPatterns = new LinkedList<String>();
//    private final List<String> filteredParams = new LinkedList<String>();

    public static LinkPreprocessor getInstance() {
        return instance;
    }

    private LinkPreprocessor() {
    }

    public String preprocess(String link, String location) {
//        log.debug("Preprocessing link '" + link + "'");
        HashMap<String, String> result = new HashMap<String, String>();
        int start = StringUtils.indexOfAny(link, "?&");
        if (start != -1) {
            String query = link.substring(start + 1);
            if (StringUtils.isNotBlank(query)) {
                String[] tokens = query.split("&");
                for (String token : tokens) {
                    String[] strings = token.split("=");
                    if (strings.length == 1) {
                        result.put(strings[0], "");
                    } else if (strings.length == 2){
                        result.put(strings[0], strings[1]);
                    } else {
                        log.error("Something bad happend : '" + token + "'");
                    }
                }
            }
        }
        filterParams(result);
//        log.debug("Preprocessing link " + link);
//        link = applyFilters(link);
        if (start != -1){
            link = link.substring(0, start);
            for (Map.Entry<String, String> entry : result.entrySet()) {
                link += "&" + entry.getKey() + "=" + entry.getValue();
            }
            link = link.replaceFirst("&", "?");
        }
        return link;
    }

    private void filterParams(Map<String, String> urlParams) {
        if (retainParamsPatterns.isEmpty()) return;
        if (retainParamsPatterns.contains("")) {
            urlParams.clear();
            return;
        }
        for (String regexp : retainParamsPatterns) {
            Pattern pattern = Pattern.compile(regexp);
            for (Iterator<Map.Entry<String, String>> it = urlParams.entrySet().iterator(); it.hasNext();) {
                Map.Entry<String, String> entry = it.next();
                String paramName = entry.getKey();
                if (!pattern.matcher(paramName).find()) {
                    log.debug("Dropping param " + paramName);
                    it.remove();
                }
            }
        }
    }

    public void addRetainParamsPattern(String regexp) {
        retainParamsPatterns.add(regexp);
    }

}
